import router from '@/router'
import Axios, { type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage, type MessageOptions } from 'element-plus'
const instance = Axios.create({
    baseURL: "/api",
    timeout: 6000,
})


//前置拦截器
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const token = sessionStorage.getItem('token')
    if (token) config.headers['token'] = token
    return config
})

//响应拦截器
instance.interceptors.response.use((resp: AxiosResponse) => {

    if (resp.status !== 200) {
        return Promise.reject(resp.statusText)
    }

    const data = resp.data
    if (data.code !== 200) {
        ElMessage.error({
            message: data.msg
        } as MessageOptions)
        //没有登录
        if (data.code === 401) {
            router.push('/login')
            return Promise.reject(data.msg)
        }
        //其他错误
        return Promise.reject(data.msg)
    }

    return Promise.resolve(data)
})

export default instance